<?php defined('SYSPATH') or die('No direct script access.');

class Login_Model extends Model {
	public function initialize() {
		$db = Database::instance();
		$db->query('BEGIN');
		try {
			$sql = 'SELECT count(*) as exist_admin FROM users WHERE username = ?';
			$query = $db->query($sql, array('admin'));
			if ($query->current()->exist_admin <= 0) {
				$sql = 'INSERT INTO users 
						(email, username, password, logins, last_login)
						VALUES(?,?,?,?,?)';
				$query = $db->query($sql, array('admin@localhost.com', 'admin', Auth::instance()->hash_password('admin',FALSE), 0, NULL));

				$sql = 'SELECT id 
						FROM users 
						WHERE (username=?)';
				$id = $db->query($sql, array('admin'))->current()->id;
				
				$sql = 'INSERT INTO profiles 
						(id, prefix_id, firstname, lastname, birthdate, sex, question_id, answer, status, expire_date, member_type, picture, created, updated)
						VALUES(?,?,?,?,CURDATE(),?,?,?,?,CURDATE() + INTERVAL 100 YEAR,?,?,CURRENT_TIMESTAMP(),?)';
				$query = $db->query($sql, array($id, NULL, 'Administrator', 'Hyper Space Music', 1, NULL, NULL, 1, 2, 'media/upload/pictures/profiles/admin.jpg', NULL));
				
				$sql = 'INSERT INTO roles_users 
						(user_id, role_id) 
						VALUES(?, ?)';
				$query = $db->query($sql, array($id, 1));	// Login
				$query = $db->query($sql, array($id, 2));	// Admin
				$query = $db->query($sql, array($id, 3));	// Member
				$query = $db->query($sql, array($id, 4));	// VIP
			}
			$db->query('COMMIT');
		}	
		catch (Exception $e) {
			$db->query('ROLLBACK');
			Kohana::log('error', $e);
		}	
	}
}